package com.cmict.data.infra.push;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmict.data.infra.controller.admin.message.vo.NotifyInfo;
import com.cmict.data.infra.dal.dataobject.message.Announcement;
import com.cmict.data.infra.dal.dataobject.message.UserAnnouncement;
import com.cmict.data.infra.dal.mysql.message.AnnouncementMapper;
import com.cmict.data.infra.dal.mysql.message.UserAnnouncementMapper;
import com.cmict.data.infra.enums.message.AnnouncementStatusEnum;
import com.cmict.data.infra.enums.message.NotifyChannelEnum;
import com.cmict.data.infra.service.message.UserAnnouncementService;
import com.cmict.data.system.api.user.dto.AdminUserRespDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息通知站内推送
 *
 * @author Hccake 2020/12/21
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class StationNotifyPusher implements NotifyPusher {

    private final ApplicationEventPublisher publisher;

    private final UserAnnouncementService userAnnouncementService;

    private final UserAnnouncementMapper userAnnouncementMapper;

    private final AnnouncementMapper announcementMapper;

    /**
     * 当前发布者对应的接收方式
     *
     * @return 推送方式
     * @see NotifyChannelEnum
     */
    @Override
    public Integer notifyChannel() {
        return NotifyChannelEnum.STATION.getValue();
    }

    @Override
    public void push(NotifyInfo notifyInfo, List<AdminUserRespDTO> userList) {
        //当有查库记录时，清理掉所有该公告的关联关系，重新插入
        if (userAnnouncementMapper.selectCount(UserAnnouncement::getAnnouncementId, notifyInfo.getId()) > 0) {
            QueryWrapper<UserAnnouncement> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(UserAnnouncement::getAnnouncementId, notifyInfo.getId());
            userAnnouncementMapper.delete(queryWrapper);
        }
        Announcement announcement=new Announcement();
        announcement.setId(notifyInfo.getId());
        announcement.setSendTime(LocalDateTime.now());
        announcement.setStatus(AnnouncementStatusEnum.PUBLISHED.getValue());
        announcementMapper.updateById(announcement);
        userAnnouncementService.prodUserAnnouncement(userList, notifyInfo.getId());
        // TODO 发布事件，监听者进行实际的 websocket 推送
//		publisher.publishEvent(new StationNotifyPushEvent(notifyInfo, userList));
    }

}
